package com.example.smartall.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.smartall.R;
import com.example.smartall.adapter.NewsListAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.entity.HomeBannerBean;
import com.example.smartall.entity.NewsBean;
import com.example.smartall.entity.NewsTypeBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.view.SListView;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * 新闻模块
 *
 * 轮播图似乎没有找到api
 *
 */
public class NewsActivity extends BaseActivity {
    private Banner banner;
    private TabLayout tab;
    private SListView list;
    //轮播图数据
    private HomeBannerBean bannerBean;
    //新闻数分类据
    private List<NewsTypeBean.DataBean> dataBeans;
    //新闻分类id
    private List<Integer> newsType = new ArrayList<>();
    //新闻数据
    private List<NewsBean.RowsBean> newsBeans;
    //新闻list适配器
    private static NewsListAdapter newsListAdapter;
    private MHandler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        handler = new MHandler();
        init();
        getBannerUrl();
        getNewsType();
        initEvent();
    }

    @Override
    public void init() {
        banner = (Banner) findViewById(R.id.banner);
        tab = (TabLayout) findViewById(R.id.tab);
        list = (SListView) findViewById(R.id.list);

        dataBeans = new ArrayList<>();
        newsType = new ArrayList<>();
        newsBeans = new ArrayList<>();
    }

    @Override
    public void initEvent() {
        //banner跳转详情
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {
                if (bannerBean.getRows().get(i).getTargetId() < 0) return;
                Intent intent = new Intent(NewsActivity.this, NewsDetailsActivity.class);
                intent.putExtra("key",bannerBean.getRows().get(i).getTargetId());
                startActivity(intent);
            }
        });
        tab.setTabMode(TabLayout.MODE_SCROLLABLE);
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //若新闻分类数据为空 不加载
                if (newsType.size() == 0) return;
                getNews();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
    //轮播数据
    private void getBannerUrl() {
        //banner的图片地址
        List<String> urls = new ArrayList<>();
        Api.config(ApiConfig.HOME_BANNER_URL,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                bannerBean = new Gson().fromJson(res,HomeBannerBean.class);
                if (bannerBean != null && bannerBean.getCode() == 200){
                    List<HomeBannerBean.RowsBean> beans = bannerBean.getRows();
                    for (int i = 0 ; i < beans.size() ; i++){
                        urls.add(ApiConfig.BASE_URL + beans.get(i).getAdvImg());
                    }
                    banner.setImages(urls);
                    banner.setImageLoader(new ImageLoader() {
                        @Override
                        public void displayImage(Context context, Object o, ImageView imageView) {
                            Glide.with(context).load(o).into(imageView);
                        }
                    });
                    handler.sendEmptyMessage(0x03);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        });
    }

    private void getNewsType() {
        Api.config(ApiConfig.NEWS_TYPE_URL,null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsTypeBean newsTypeBean = new Gson().fromJson(res,NewsTypeBean.class);
                if (newsTypeBean != null && newsTypeBean.getCode() == 200){
                    dataBeans = newsTypeBean.getData();
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        });
    }

    //获取新闻类型后调用 新闻类型tab设置
    private void setTabData() {
        if (dataBeans != null){
            for (int i = 0 ; i < dataBeans.size() ; i++){
                TabLayout.Tab tab = this.tab.newTab();
                tab.setText(dataBeans.get(i).getName());
                //原做法是将 新闻类型 作为tag传给每一个tab，在切换tab时获取tag实现新闻分类，但是一直发生奇怪的空指针
//                tab.setTag(dataBeans.get(i).getId());
                this.tab.addTab(tab);
                newsType.add(dataBeans.get(i).getId());
            }
        }
        //获取新闻类型后立刻加载新闻
        getNews();
    }

    private void getNews() {
        HashMap<String,Object> params = new HashMap<>();
        params.put("type",newsType.get(tab.getSelectedTabPosition()));
        Api.config(ApiConfig.NEWS_URL,params).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                NewsBean newsBean = new Gson().fromJson(res, NewsBean.class);
                if (newsBean != null){
                    newsBeans = newsBean.getRows();
                    handler.sendEmptyMessage(0x02);
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("加载失败");
            }
        });
    }

    private void showNews() {
        Collections.sort(newsBeans);
        for (int i = 0 ; i < newsBeans.size() ; i++){
            Log.e("Tag",newsBeans.get(i).getPublishDate());
        }
        if (newsListAdapter == null){
            newsListAdapter = new NewsListAdapter(NewsActivity.this,newsBeans);
        }else {
            newsListAdapter.setNewsBeans(newsBeans);
        }
        list.setAdapter(newsListAdapter);
    }

    class MHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x01:
                    setTabData();
                    break;
                case 0x02:
                    showNews();
                case 0x03:
                    banner.setDelayTime(3000);
                    banner.start();
                    banner.startAutoPlay();
                    break;
            }
        }
    }
}